import prisma from '~~/lib/prisma'
import Joi from 'joi'
import md5 from 'md5'
import { Result } from '~~/lib/helper/result'
import JWT from 'jsonwebtoken'
import { omit } from 'lodash-es'
export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const schema = Joi.object({
    password: Joi.string().required(),
    phone: Joi.string().pattern(/^1\d{10}$/),
  })
  try {
    await schema.validateAsync(body)
  } catch (error) {
    console.log('error', error)
    return Result.Error('参数错误！')
  }

  // 密码加密
  let salt = 'salt'
  let password = md5(md5(body.password) + salt)
  try {
    let user = await prisma.user.findFirst({
      where: { phone: body.phone, password: password },
    })
    if (!user) return Result.Error('账号不存在或密码错误！')
    // 生成 token
    const token = JWT.sign({ id: user.id }, 'jwt-secrect')
    return Result.Ok(
      {
        accessToken: token,
        userInfo: omit(user, 'password'),
      },
      200,
      '登录成功！'
    )
  } catch (error) {
    return Result.Error('用户登录失败！')
  }
})
